<template>
	<view class="">
		<u-popup
		@close="popClose"
		@open="popOpen"
		:mask-close-able="false"
		v-model="tcShow" border-radius="16" mode="center">
			<view class="tcShow_block">
				<view class="title">
					{{ title }}
				</view>
				<view class="flex_zhcenter">
					<image class="image" :src="logo"></image>
				</view>
				<view 
				class="flex_zhcenter smTitle font_size32 flex_column margin-bt20">
					<view class="">{{ smTitle.title1 }}</view>
					<view class="">{{ smTitle.title2 }}</view>
				</view>
				<view class="placeNum txt-ellipsis">
					<text>{{ placenum || '' }}</text>
				</view>
				<block v-if="isEmergency">
					<view class="paking-cont">
					  <text>{{mergencyMsg || '抱歉，当前泊位维护升级中,您可先行离开，驶离前再进行补扫'}}</text>
					</view>
				</block>
				<block v-else>
					<view class="time_price overfHidden margin-bt20">
						<view class="time_block flex_hcneter_bet overfHidden">
							<view class="flex_flex overfHidden flex_hcneter">
								<text class="wordBreak">驶入时间： </text>
								<text class="time font_size26 bold margin-rt20 txt-ellipsis">{{ startTime }} </text>
							</view>
							<view class="item_staColor_red money font_size36 bold">
								{{ startTimesfm }}
							</view>
						</view>
						<view class="price_block flex_hcneter_bet">
							<view class="flex_flex flex_hcneter overfHidden margin-rt20">
								<text class="wordBreak">当前费用：</text> 
								<text v-if="unpayAmount || unpayAmount===0" class="txt-ellipsis bold price font_size32 item_staColor_red">{{unpayAmount || 0}}</text>
								<text class="wordBreak item_staColor_red">元</text>
							</view>
							<view class="item_staColor_blue wordBreak" @click="shoufeibz">
								收费标准>
							</view>
						</view>
					</view>
					<view 
					v-if="startTime && parkingBenefitList.length && !carnumber" 
					class="preferential_list flex_hcneter_bet">
						<view 
						@click="tabCrd(item)" 
						v-for="(item,index) in parkingBenefitList"
						:key="index"
						:class="tabIndex == item.type ? 'item_active' : ''"
						:style="{
							'margin-right': parkingBenefitList.length == 3 ? '' : '34rpx'
						}"
						class="preferential_item flex_zhcenter">
							<image class="image" :src="item.imageUrl"></image>
							<view class="flex_flex overfHidden">
								<text class="txt-ellipsis">{{item.title}}</text>
							</view>
							<image class="frezz-icon" :src="item.frezzIcon" mode="aspectFit" v-if="item.isFrezz"/>
						</view>
					</view>
					
					<view class="tcShow_btBlock flex_zhcenter">
						<view 
						@click="$u.throttle(parkche, 600)"
						:style="{
							background: 'linear-gradient(to bottom,'+ (unpayAmount === 0 ? '#00C6FF' : '#FA8703')
						+ ',' + (unpayAmount === 0 ? '#0072FF' : '#FD4F00') + ')'}"
						class=" tcShow_bt flex_zhcenter">
							{{tabIndex==-1? (unpayAmount === 0 ? '确认停车' : '确认并支付' ):
							(selectParkingBenefitItemInfo.verifyFree ? (unpayAmount === 0 ? '确认停车' : '确认并支付' ) : '校验车牌')}}
						</view>
					</view>
					<view class="tcShow_btBlock flex_zhcenter">
						<view 
						v-if="startTime && wxScorePayStatusObj.openType === 2 && !parkingBenefitList.length"
						class=" tcShow_bt flex_zhcenter green">
							先享后付停车
						</view>
					</view>
				</block>
				
				
				<view class="close" @click="close">
					<u-icon size="40" name="close"></u-icon>
				</view>
			</view>
		</u-popup>
		
		
		<!--优惠券弹窗领取-->
		<coupReceive 
		id="couponReceive" 
		:drawId="drawId" 
		drawType="park" 
		ref="couponReceive"
		@close="onCouponReceiveDialogClose"></coupReceive>
		
		<!-- 提示 -->
		<tipsPop 
		:popCont="popCont"
		:popsmTitle="popsmTitle"
		@close="closeTips" 
		@confim="confimTips"
		:popShow="popShow" 
		:btModel="btModel"
		:popTitle="popTitle"
		:maskClose="maskClose"
		:contModel="contModel"
		:popbtCancel="popbtCancel"
		:bottomCloseIcon="bottomCloseIcon"
		:popbtConfim="popbtConfim">
			<view 
			v-if="popTitle == '收费标准与停车说明'"
			class="" slot="cont_text">
				<view class="sfxq">收费详情：</view>
				<rich-text  :nodes="ruleDetail"></rich-text>	
				<view class="sfxq">停车说明：</view>
				<rich-text  :nodes="warning"></rich-text>	
			</view>
		</tipsPop>
	</view>
	
</template>

<script>
	import  { imgPath } from '@/static/imgPath.js'
	import { parkche,getTipPop,closeTips,confimTips,handlePayScoreConfirmParking,getFeeRule,parkingInfo } from '@/utils/parkComm.js'
	import { ScanException } from '@/pages/parkingLot/js/ScanExceptions.js'
	import BlueTooth from './blueTooth'
	
	import coupReceive from '@/components/coup-receive/index.vue';
	import tipsPop from '@/components/tipsPop/index.vue'
	import { getUserInfo } from '@/commApi/dingcengApi/index.js'
	export default {
	  name: "index",
	  components: {
	    coupReceive,tipsPop,
	  },
		data() {
		  return {
				popTitle:'温馨提示',
				popCont:'',//弹窗内容
				bottomCloseIcon:false,
				popShow:false,//
				maskClose:true,//点击遮罩是否关闭
				popsmTitle:'',
				btModel:4,
				popbtCancel:'8秒后自动返回首页',//弹窗底部
				popbtConfim:'确认',
				contModel:3,
				popCont:'',//弹窗内容
				drawId: "", //抽奖ID
				mergencyMsg: '', // 应急模式提示信息
				ruleDetail: '', // 收费规则相关字段
				warning: '', // 收费规则相关字段
				spType: '',
				pkParkrecordId: '', // 停车记录id
				type: 5, // 停车方式，5表示通过蓝牙停车
				carnumber: '', // 车牌号
				tabIndex: -1, // -1| 表示选了普通停车，>-1表示选了优惠停车
				selectParkingBenefitItemInfo: {} ,// 选中的福利停车项数据
				parkingBenefitList: [], // 福利停车列表
				wxScorePayStatusObj: { openType: 0,  payScoreStatus: 0, mchId: 1, orgId: 1 }, // 支付分功能相关字段，openType 是否开通支付分 0|未开通 1|免确认 2|需确认；payScoreStatus 免确认模式的授权状态 0|未授权 1|授权中 2|已授权 3|关闭中 4|已关闭
				imgPath,//图片地址
				isEmergency: false, // 是否显示应急模式
				placenum: '', // 泊位号
				startTime: '', // 驶入日期
				startTimesfm: '', // 驶入的具体时间
				unpayAmount: '', // 未支付金额
				tcShow:false,//停车和弹窗显示
				innerAudioContext: uni.createInnerAudioContext(),//语音播报
				scanException: null,
				blueToothInstance: null,
				pageMark: 'blueToothRecognition', // 页面标识
		  };
		},
		props: {
			logo: {//
				type: [String],
				default:()=>{
					return '/static/parking/tccg.png'
				}
			},
			title: {//标题
				type: [String],
				default:()=>{
					return '提示'
				}
			},
			smTitle: {//小标题
				type: [Object],
				default:()=>{
					return {
						title1:'系统检测到您所停泊位',
						title2:'请核对信息后确认停车',
					}
				}
			},
		},
	  mounted() {
	    
	  },
		destroyed() {
			if(this.innerAudioContext){
				this.innerAudioContext.stop()
			}
		},
	  methods: {
			parkche(){//停车按钮点击
				parkche(this)
			},
			tabCrd(e){//选择支付形式
				tabCrd(this,e)
			},
			shoufeibz(){//收费标准
				this.getTipPop({
					popCont:'',popTitle:'收费标准与停车说明',btModel:1,
					contModel:1,popbtCancel:'关闭',popbtConfim:'',popsmTitle:'',
				})
			},
			getTipPop(obj){
				getTipPop(this,obj)
			},
			closeTips(){//规则弹窗关闭
				closeTips(this)
			},
			confimTips(e){//规则弹窗确认
				confimTips(this,e)
			},
			popClose(){//弹窗关闭
				this.$emit('popClose')
			},
			waiopen(e){//从外部传入打开弹窗
				this.tcShow = e
			},
			popOpen(){//弹窗开启
				this.innerAudioContext = uni.createInnerAudioContext();
				this.pageMark = 'blueToothRecognition'
				setTimeout(() => {
				  this.useBlueTooth()
				}, 500);
			},
			close(){//点击按钮关闭
				this.tcShow = false
				this.scanException.reportTbscanException(2)
				this.innerAudioContext.stop()
				this.$emit('close')
			},
			/**
			 * 使用蓝牙模块前，判断是否有权限
			 */
			async useBlueTooth() {
			  // 通过configs，拿到有权限的用户手机号
				let configs = uni.getStorageSync('configs') || {}
				let can_use_bluetooth_user = configs.can_use_bluetooth_user || ''
			  let list = can_use_bluetooth_user.split(',')
			  let userInfo = uni.getStorageSync('userInfo')
			  if (!userInfo) {
			    let res = await getUserInfo()
			    if(res.code != 200) return
			    uni.setStorageSync('userInfo', res.data)
			    userInfo = res.data
			  }
			  let myPhonenum = userInfo.phone || ''
			  if (list.includes(myPhonenum)) {
			    this.startBlueToothConnect()
			  }
			},
			async startBlueToothConnect() {
			  this.blueToothInstance = new BlueTooth()
			  let initBlueToothRes = await this.blueToothInstance.initBlueTooth()
			  if (initBlueToothRes) {
			    await this.blueToothInstance.startBluetoothDevicesDiscovery()
			    setTimeout(async () => {
			      await this.blueToothInstance.stopBluetoothDevicesDiscovery()
			      const res = await this.blueToothInstance.getBluetoothDevices()
			      this._dealwithBlueToothResult(res)
			      await this.blueToothInstance.closeBluetoothAdapter()
			    }, 2000);
			  }
			},
			/**
			 * 处理蓝牙接收的数据，筛选name字段格式符合的设备，再取信号前三强的设备给服务端
			 * @param {*} result 
			 */
			async _dealwithBlueToothResult(result) {
			  if (result.devices && result.devices.length) {
			    let list = result.devices.filter(item => {
			      const snCodeArr = item.name.split('&')
			      if (snCodeArr[1] && snCodeArr[1].includes('PQRN')) return false
			      return snCodeArr[0] && !isNaN(snCodeArr[0]) && snCodeArr[0].length >= 15
			    })
			    if (list.length) {
			      list.sort((a,b) => (b.RSSI - a.RSSI))
			      const targetList = list.splice(0, 3)
			      console.log('信号前三强列表', targetList, '被筛掉的列表', list)
			      const param = {
			        bluetoothId: targetList.map(item => (item.name.split('&')[0])).join(',')
			      }
			      console.log('get placenum', param)
			      let res = await this.$u.api.sendNearParkingPlaceNum(param)
						if(!res) return
						let data = res.data
						if (data) {
						  this.data.placenum = res.data
						  this._initScanException(res.data)
						  this.getFeeRule()
						  this.parkingInfo()
						}
			    }
			  }
			},
			//验证是否停车
			async parkingInfo(placenums) {
				parkingInfo(this,placenums)
			},
			_initScanException(placenum) {
			  this.scanException = new ScanException(placenum)
			},
			//查询收费规则
			async getFeeRule() {
				getFeeRule(this)
			},
	  }
	};
</script>

<style lang="less" >
	.tcShow_block{
		padding: 30rpx 30rpx 46rpx;width: 600rpx;box-sizing: border-box;
		position: relative;
		.close{
			position: absolute;top: 30rpx;right: 30rpx;
		}
		.paking-cont{
		  color: #FF0000;
		  font-size: 36rpx;
		}
		.tcShow_btBlock{
			.tcShow_bt{
				width: 476rpx;height: 74rpx;border-radius: 80rpx;margin-top: 46rpx;
				background: linear-gradient(to bottom, #00C6FF,#0072FF);color: #fff;
			}
			.green{background: linear-gradient(to bottom, rgba(42, 174, 103,0.7) , #2AAE67);}
		}
		.preferential_list{
			.preferential_item{
				border-radius: 16rpx;border: 2rpx solid #E5F1FF;margin-right: 20rpx;
				background-color: #E5F1FF;font-size: 22rpx;padding: 14rpx 14rpx;position: relative;
			}
			.item_active{border: 2rpx solid #007AFF;}
			.image{width: 35rpx;height: 35rpx;margin-right: 8rpx;}
			.frezz-icon{
				position: absolute;
				top: -4rpx;
				right: 0;
				width: 61rpx;
				height: 54rpx;
			}
		}
		.title{
			font-size: 36rpx;text-align: center;margin-bottom: 10rpx;
		}
		.image{width: 166rpx;height: 139rpx;}
		.smTitle{color: #646464;}
		.placeNum{
			border-radius: 18rpx;background-color: #F6F9FE;height: 108rpx;
			line-height: 108rpx;text-align: center;font-size: 92rpx;
			color: #007AFF;font-weight: bold;margin-bottom: 10px;
		}
		.time_price{
			background-color: #F6F9FE;border-radius: 18rpx;
			font-size: 22rpx;color: #393939;
			.time_block{
				height: 66rpx;padding: 0 10rpx;
				.time{}
				.money{}
			}
			.price_block{
				height: 66rpx;padding: 0 10rpx;
				.price{}
			}
		}
	}
</style>